import 'dart:io';

import 'package:flutter/material.dart';
import 'package:kunlun_gas/app_files.dart';
import 'package:photo_view/photo_view.dart';
import 'package:photo_view/photo_view_gallery.dart';
import 'fileimage_ex.dart';
import 'package:image_cropper/image_cropper.dart';
import 'package:cached_network_image/cached_network_image.dart';

class GalleryExampleItem {
  GalleryExampleItem({this.id, this.resource, this.isSvg = false});

  final String id;
  final dynamic resource;
  final bool isSvg;
}

class GalleryPhotoViewWrapper extends StatefulWidget {
  GalleryPhotoViewWrapper(
      {this.loadingChild,
        this.backgroundDecoration = const BoxDecoration(
          color: Colors.black,
        ),
        this.initialIndex,
        @required this.galleryItems,
        this.editModel = false})
      : pageController = PageController(initialPage: initialIndex);

  final Widget loadingChild;
  final Decoration backgroundDecoration;
  final int initialIndex;
  final PageController pageController;
  final List<GalleryExampleItem> galleryItems;
  final bool editModel;

  @override
  State<StatefulWidget> createState() {
    return _GalleryPhotoViewWrapperState();
  }
}

class _GalleryPhotoViewWrapperState extends State<GalleryPhotoViewWrapper> {
  int currentIndex;
  List<GalleryExampleItem> _galleryItems = [];

  @override
  void initState() {
    currentIndex = widget.initialIndex;
    _galleryItems.clear();
    _galleryItems.addAll(widget.galleryItems);
    super.initState();
  }

  @override
  void didUpdateWidget(GalleryPhotoViewWrapper oldWidget) {
    super.didUpdateWidget(oldWidget);
    _galleryItems.clear();
    _galleryItems.addAll(widget.galleryItems);
  }

  void onPageChanged(int index) {
    setState(() {
      currentIndex = index;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
          decoration: widget.backgroundDecoration,
          constraints: BoxConstraints.expand(
            height: MediaQuery.of(context).size.height,
          ),
          child: Stack(
            alignment: Alignment.bottomRight,
            children: <Widget>[
              PhotoViewGallery.builder(
                scrollPhysics: const BouncingScrollPhysics(),
                builder: _buildItem,
                itemCount: widget.galleryItems.length,
                loadingChild: widget.loadingChild,
                backgroundDecoration: widget.backgroundDecoration,
                pageController: widget.pageController,
                onPageChanged: onPageChanged,
              ),
              Positioned(
                bottom: 30,
                width: MediaQuery.of(context).size.width,
                child: Center(
                  child: Text(
                    "${currentIndex + 1}/${widget.galleryItems.length}",
                    style: const TextStyle(
                        color: Colors.white, fontSize: 17.0, decoration: null),
                  ),
                ),
              ),
              Positioned(
                top: 6,
                left: 0,
                child: InkWell(
                  onTap: () => Navigator.pop(context, _galleryItems),
                  child: widget.editModel
                      ? Container(
                    width: 90,
                    height: MediaQuery.of(context).padding.top + 80,
                    child: Center(
                      child: Text(
                        '下一步',
                        style: TextStyle(color: Colors.white),
                      ),
                    ),
                  )
                      : Container(
                    width: 60,
                    height: MediaQuery.of(context).padding.top + 80,
                    child: Icon(CupertinoIcons.back,color: Colors.white,),
                  ),
                ),
              ),
              widget.editModel
                  ? Positioned(
                top: 6,
                right: 0,
                child: InkWell(
                  onTap: () async {
                    var item = _galleryItems[currentIndex].resource;
                    if (item.runtimeType.toString() == '_File') {
                      File file = await ImageCropper.cropImage(
                        sourcePath: item.path,
                      );
                      if (file != null)
                        setState(() {
                          _galleryItems.replaceRange(
                              currentIndex, currentIndex + 1, [
                            GalleryExampleItem(
                                id: '$currentIndex', resource: file)
                          ]);
                        });
                    }
                  },
                  child: Container(
                    width: 90,
                    height: MediaQuery.of(context).padding.top + 80,
                    child: Center(
                      child: Text(
                        '调整',
                        style: TextStyle(color: Colors.white),
                      ),
                    ),
                  ),
                ),
              )
                  : Container(),
            ],
          )),
    );
  }

  PhotoViewGalleryPageOptions _buildItem(BuildContext context, int index) {
    final GalleryExampleItem item = _galleryItems[index];
    return PhotoViewGalleryPageOptions(
      imageProvider: item.resource is File
          ? FileImageEx(item.resource)
          : CachedNetworkImageProvider(NetworkConfig.imageUrl(item.resource)),
      initialScale: PhotoViewComputedScale.contained,
      minScale: PhotoViewComputedScale.contained * (0.5 + index / 10),
      maxScale: PhotoViewComputedScale.covered * 1.1,
      heroTag: item.id,
    );
  }
}
